package com.lcsolute.admin.service.impl;

import java.util.HashMap;
import java.util.Map;
import java.util.Objects;

import com.lcsolute.token.domain.ResponseResult;
import com.lcsolute.token.domain.entity.LoginUser;
import com.lcsolute.token.domain.entity.User;
import com.lcsolute.admin.service.LoginService;
import com.lcsolute.admin.utils.JwtUtil;
import com.lcsolute.admin.utils.RedisCache;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.stereotype.Service;

@Service
public class LoginServiceImpl implements LoginService{

    @Autowired
    private AuthenticationManager authenticationManager;

    @Autowired
    private RedisCache redisCache;

    @Override
    public ResponseResult login(User user) {
        // AuthenticationManager authenticate 进行用户认证
        UsernamePasswordAuthenticationToken authenticationToken = new UsernamePasswordAuthenticationToken(user.getUserName(), user.getPassword());
        Authentication authentication =authenticationManager.authenticate(authenticationToken);

        // 如果认证没有通过，给出对应的提示
        if (Objects.isNull(authentication)) {
            throw new RuntimeException("登录失败");
        }

        // 如果认证通过了，使用 userid 生成 jwt
        LoginUser loginUser= (LoginUser) authentication.getPrincipal();
        String userId = loginUser.getUser().getId().toString();
        String jwt = JwtUtil.createJWT("3");
        Map<String, String> map = new HashMap<>();
        map.put("token", jwt);

        // 把完整的用户信息存入 redis userid 作为 key
       redisCache.setCacheObject("login:"+userId, loginUser);
        return new ResponseResult(200, "登录成功", map);
    }

    @Override
    public ResponseResult<User> logout() {
        // 获取 SecurityContextHolder 中的用户id
        UsernamePasswordAuthenticationToken authenticationToken = (UsernamePasswordAuthenticationToken) SecurityContextHolder.getContext().getAuthentication();
        LoginUser loginUser = (LoginUser) authenticationToken.getPrincipal();
        Long userid = loginUser.getUser().getId();
        // 删除 redis 中的值
        redisCache.deleteObject("login:"+userid);
        return new ResponseResult<>(200, "注销成功");
    }
    
}
